package org.mj.im.common.id;

import java.util.concurrent.ConcurrentHashMap;

public class SnowFlakeFactory {
    private static final long DEFAULT_DATACENTER_ID = 1;
    private static final long DEFAULT_MACHINE_ID = 1;

    private static final String DEFAULT_SNOW_FLAKE = "snow_flake";
    private static final ConcurrentHashMap<String,SnowFlake> snowFlakeCache = new ConcurrentHashMap<>();
    public static SnowFlake get(long datacenterId, long machineId) {
        return new SnowFlake(datacenterId, machineId);
    }
    public static SnowFlake get(){
        return new SnowFlake(DEFAULT_DATACENTER_ID, DEFAULT_MACHINE_ID);
    }
    public static SnowFlake getFromCache(){
        return snowFlakeCache
                .computeIfAbsent(DEFAULT_SNOW_FLAKE,
                        (key)-> new SnowFlake(DEFAULT_DATACENTER_ID,DEFAULT_MACHINE_ID)
                );
    }
    public static SnowFlake getByDatacenterIdAndMachineId(long datacenterId, long machineId) {
        if (datacenterId > SnowFlake.getMaxDatacenterNum() || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId must be greater than 0 and less than " + SnowFlake.getMaxDatacenterNum());
        }
        if (machineId > SnowFlake.getMaxMachineNum() || machineId < 0) {
            throw new IllegalArgumentException("machineId must be greater than 0 and less than" + SnowFlake.getMaxMachineNum());
        }
        String key = DEFAULT_SNOW_FLAKE + "_" + datacenterId + "_" + machineId;
        return snowFlakeCache.computeIfAbsent(key,k-> new SnowFlake(datacenterId, machineId));
    }


    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.println(getFromCache().nextId());
        }
    }
}
